package com.example.java250729_springboot.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {
    @PostMapping("/login")
    public Boolean login(String userName, String password, HttpSession session){
        //1.参数校验(基本校验，是否为空，参数范围....)
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return false;
        }
        //2.判断密码是否正确
        //TODO 暂且写死
        if ("admin".equals(userName) && "admin".equals(password)){
            //存储session
            session.setAttribute("loginUser",userName);
            return true;
        }

        //不建议使用这个方法，可读性低  开发规范：嵌套不超过五层，下面已经四层
//        if (StringUtils.hasLength(userName) && StringUtils.hasLength(password)){
//            if ("admin".equals(userName) && "admin".equals(password)){
//                return true;
//            }
//        }

        return false;
    }
    @GetMapping("/getLoginUser")
    public String getLoginUser(HttpServletRequest request){
        //参数为false ，获取的session为null，不会创建session
        HttpSession session = request.getSession(false);
        if (session != null){
            String loginUser = (String)session.getAttribute("loginUser");
            return loginUser;
        }
        return "";
    }
}































